<template>
  <div>
    <a-modal :visible="visible" :title="title" :bodyStyle="{
      padding: '20px 60px',
    }" :width="700" :footer="null" @cancel="cancelClick" :maskClosable="false" :keyboard="false">
      <a-form :label-col="{ span: 6 }">
        <a-form-item label="项目名称" v-bind="validateInfos.name">
          <a-input v-model:value="modelRef.name" placeholder="请输入项目名称" />
        </a-form-item>
        <a-form-item label="项目LOGO" v-bind="validateInfos.logo" extra="大小2M以下，图片格式必须为jpeg,png，建议尺寸360*360px">
          <a-upload :action="$utils.imgAction" :headers="{ 'org-token': $store.getters.token }" @preview="handlePreview"
            v-model:file-list="fileList" @change="handleUploadChange" :multiple="false" name="image"
            :data="{ dir: 'work_ai' }" accept=".png,.jpg,.jpeg" list-type="picture-card">
            <div v-if="!fileList.length">
              <PlusOutlined />
              <div>上传图片</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="关联抖音位置">
          <section class="hide-scroller-bar" style="
              max-height: 240px;
              overflow: auto;
              padding-right: 5px;
              margin-bottom: 10px;
            " v-if="poiList.length">
            <a-row class="poi-list" justify="space-between" align="middle" v-for="(item, index) in poiList"
              :key="item.id">
              <a-col :span="16">
                <div style="font-weight: 700">{{ item.store_name }}</div>
                <div>{{ item.store_address }}</div>
              </a-col>
              <a-col>
                <a-space>
                  <a-button type="text" style="color: #2878ff" @click="editPOIClick(item)">编辑</a-button>
                  <a-button type="text" style="color: #2878ff" @click="deletPOIClick(item, index)">删除</a-button>
                </a-space>
              </a-col>
            </a-row>
          </section>

          <a-row>
            <a-col :span="16" style="margin-right: 5px">
              <a-select v-model:value="storeName" mode="multiple" placeholder="请选择关联项目" style="max-width: 300px"
                :filter-option="false" :not-found-content="fetching ? undefined : null" :options="selectList"
                @search="fetchUser" @change="selectChange" :maxTagCount="1" :maxTagTextLength="5" allowClear>
                <template v-if="fetching" #notFoundContent>
                  <a-spin size="small" />
                </template> </a-select></a-col>

            <a-col :span="6" style="margin-left: 5px">
              <a-button @click="addPOI" ghost type="primary" style="
                  border: 1px solid #e0e0e6;
                  color: #000;
                  border-radius: 6px;
                ">添加POI</a-button>
            </a-col>
          </a-row>
        </a-form-item>
        <!-- <a-form-item
          label="可绑定员工IP数"
          v-bind="validateInfos.bind_employee_number"
        >
          <a-row align="middle">
            <a-col>
              <a-radio-group v-model:value="bind_employee_number">
                <a-radio :value="-1">不限</a-radio>
                <a-radio :value="1">自定义</a-radio>
              </a-radio-group>
            </a-col>
            <a-col>
              <a-space>
                <a-input-number
                  v-if="bind_employee_number == 1"
                  v-model:value="modelRef.bind_employee_number"
                  placeholder="请输入"
                  addon-after="个"
                />
                <a-tooltip>
                  <template #title
                    >此项目可绑定的抖音账号数量上限，员工IP账号数量会共用可绑定账号的额度，当账号总额度用完时项目将无法再绑定员工IP账号
                  </template>
                  <question-circle-outlined />
                </a-tooltip>
              </a-space>
            </a-col>
            <a-col> </a-col>
          </a-row>
        </a-form-item> -->
        <div>
          <div>说明：</div>
          <div>1、新建项目时，将自动创建项目的素材目录</div>
          <div>2、添加POI后，可以在视频发布等场景中，快速使用并携带POI信息</div>
        </div>
      </a-form>
      <div class="footer">
        <a-space>
          <a-button ghost type="primary" style="border: 1px solid #e0e0e6; color: #000; border-radius: 6px"
            @click="cancelClick">取消</a-button>
          <a-button type="primary" style="background: #2878ff; border: none; border-radius: 6px" @click="submitClick"
            :loading="loading">{{ detailId ? "保存" : "创建" }}</a-button>
        </a-space>
      </div>
    </a-modal>

    <!-- 添加POI -->
    <AddPOI :visible="visiblePOI" @onCancel="visiblePOI = false" @onSubmit="successPOI" :id="poiId" />
  </div>

  <baseModel ref="dialog" :contentWidth="'400px'" :zIndex="1011" :maskClosable="true" :centered="false"
    :closable="true">
    <template #title>
      <div class="title_box">
        <span class="title">LOGO预览</span>
      </div>
    </template>
    <template #content>
      <div class="loding_content">
        <img :src="imgUrl" alt="" style="width: 100%; height: 100%" />
      </div>
    </template>
    <template #footer>
      <a-button type="primary" @click="dialog.closeModal()">确定</a-button>
    </template>
  </baseModel>
</template>

<script>
import {
  reactive,
  toRefs,
  ref,
  computed,
  defineComponent,
  watch,
  createVNode,
  onMounted,
} from "vue";

import baseModel from "@/components/baseModel/baseModel.vue";


import { Form, message, Modal } from "ant-design-vue";
import utils from "@/common/utils/utils.js";
import {
  QuestionCircleOutlined,
  PlusOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import AddPOI from "./AddPOI.vue";
import request from "../../../../common/utils/request";
const useForm = Form.useForm;
import _ from "lodash";
export default defineComponent({
  name: "NewClip",
  components: {
    QuestionCircleOutlined,
    PlusOutlined,
    AddPOI,
    baseModel
  },
  setup(props, { emit }) {
    const state = reactive({
      count: 0,
      loading: false,
      fileList: [
        {
          uid: "admin_logo",
          name: "logo.png",
          status: "done",
          url: utils.staticPath + "images/workAi/shotstack/Moren_icon.png",
        },
      ],
      visiblePOI: false,
      bind_employee_number: -1,
      poiId: 0, //对应的id
      poiList: [],
      storeName: [], //商家名称
      selectList: [], //店铺名称下拉列表
      fetching: false, //是否正在搜索下拉
      selectData: [],
      visible: false, //控制弹窗显示隐藏
      detailId: null, //详情id
      title: "", //弹窗标题
    });
    // 打开弹窗
    const showModal = (id) => {
      state.poiList = []; //先清空
      state.storeName = []; //先清空
      // 修改
      if (id) {
        state.detailId = id; //详情id
        state.title = "编辑项目";
        getDdetail();
      } else {
        console.log(id, '从哪来的呢');
        console.log(state.detailId, '从哪来的呢');
        // 新增
        state.title = "新增项目";
        state.bind_employee_number = -1;
        state.fileList = [
          {
            uid: "admin_logo",
            name: "logo.png",
            status: "done",
            url: utils.staticPath + "images/workAi/shotstack/Moren_icon.png",
          },
        ];
      }
      state.visible = true; //打开弹窗
      getSelectList(); //获取下拉列表
    };
    watch(
      () => state.bind_employee_number,
      (val) => {
        if (val == 1) {
          rulesRef.bind_employee_number[0].required = true;
          if (props.id) {
            modelRef.bind_employee_number = undefined;
            return;
          }
          modelRef.bind_employee_number = undefined;
        } else {
          rulesRef.bind_employee_number[0].required = false;
          if (props.id) {
            return;
          }
          modelRef.bind_employee_number = -1;
        }
      }
    );
    // 表单
    const modelRef = reactive({
      name: "",
      bind_employee_number: -1,
      logo: utils.staticPath + "images/workAi/shotstack/Moren_icon.png",
    });
    // 表单校验规则
    const rulesRef = reactive({
      name: [
        {
          required: true,
          message: "请输入项目名称",
        },
      ],
      logo: [
        {
          required: true,
          message: "请上传项目LOGO",
        },
      ],
      bind_employee_number: [
        {
          required: false,
          message: "请输入项目IP账号数",
        },
      ],
      poiList: [{ required: false, message: "请选择" }],
    });
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    // 上传图片
    const handleUploadChange = (info) => {
      // debugger
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList.map((file, index) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
            } else {
              message.warning(file.response.msg);
              resFileList.splice(index, 1);
            }
          }
        });
      }
      state.fileList = resFileList;
      console.log(state.fileList, "state.fileList");
      if (state.fileList.length) {
        modelRef.logo = state.fileList[0]?.url;
      } else {
        modelRef.logo = "";
      }
    };

    const imgUrl = ref('')
    const dialog = ref(null)
    // 预览图片
    const handlePreview = (file) => {
      imgUrl.value = file?.url || file.thumbUrl || ''
      if (imgUrl.value) {
        // dialog.value && dialog.value.closeModal()
        dialog.value && dialog.value.showModal();
      }
    }

    // 新增POI
    const addPOI = () => {
      state.poiId = 0;
      state.visiblePOI = true;
    };
    // 新增POI子组件成功回调
    const successPOI = (data) => {
      console.log(data);
      // 修改
      if (state.poiId) {
        state.poiList = state.poiList.map((item) => {
          if (item.id == state.poiId) {
            return (item = data);
          } else {
            return item;
          }
        });
        state.visiblePOI = false;
        return;
      }
      // 新增
      state.poiList.push(data);
      getSelectList();
      state.storeName.push(data.id);
      state.visiblePOI = false;
    };
    // 关闭弹窗
    const cancelClick = () => {
      resetFields(); //清空表单
      state.visible = false; //关闭弹窗
      state.detailId = null
      state.fileList= []
    };

    const editPOIClick = (item) => {
      state.poiId = item.id;
      state.visiblePOI = true;
    };

    const deletPOIClick = (item, index) => {
      // if (state.detailId) {
      Modal.confirm({
        title: `确定删除吗？`,
        icon: createVNode(ExclamationCircleOutlined),
        cancelText: "取消",
        okText: "确定",
        onOk() {
          const indexId = state.poiList.findIndex((i) => i.id == item.id);
          state.poiList.splice(indexId, 1);
          let store_ID = state.storeName.findIndex(
            (ele) => ele.id == item.id
          );
          state.storeName.splice(store_ID, 1);
          message.success("删除成功");
        },
      });
      // }
    };

    const getFileList = () => {
      fetch(img) // 使用实际图片的路径替换这里
        .then((response) => response.blob()) // 将图片转换成Blob对象
        .then((blob) => {
          const file = new File([blob], "image.png", { type: "image/png" }); // 创建文件对象
          // 现在你可以使用这个文件对象了，比如上传到服务器或者作为表单的一部分
          return file;
        })
        .catch((e) => console.error(e));
    };
    // 提交
    const submitClick = () => {
      validate().then(() => {
        state.loading = true;
        if (state.poiList.length) {
          modelRef.poidList = state.poiList.map((item) => item.id);
        }
        // 修改
        if (state.detailId) {
          modelRef.id = state.detailId;
          request
            .put("/work_ai", "/user/shotstack/library", modelRef)
            .then(() => {
              message.success("修改成功");
              state.loading = false;
              resetFields(); //清空表单
              emit("onSubmit"); //通知父组件刷新列表
              state.visible = false; //关闭弹窗
              state.detailId = null

            })
            .finally(() => {
              state.loading = false;
              state.detailId = null

            })
            .catch(() => {
              state.loading = false;
            });
          return;
        }
        // 新增
        modelRef.id = undefined;
        console.log(modelRef, "modelRef");
        request
          .post("/work_ai", "/user/shotstack/library", modelRef)
          .then(() => {
            message.success("创建成功");
            state.loading = false;
            resetFields(); //清空表单
            emit("onSubmit"); //通知父组件刷新列表
            state.visible = false; //关闭弹窗
            state.detailId = null

          })
          .finally(() => {
            state.loading = false;
            state.detailId = null

          })
          .catch(() => {
            state.loading = false;

          });
      });
    };
    // 获取详情
    const getDdetail = () => {
      request
        .get("/work_ai", "/user/shotstack/library", { id: state.detailId })
        .then((res) => {
          sendModelRef(res.result);
          if (res.result.bind_employee_number == -1) {
            state.bind_employee_number = -1;
          } else {
            state.bind_employee_number = 1;
            setTimeout(() => {
              modelRef.bind_employee_number = res.result.bind_employee_number;
            }, 10);
          }
          if (res.result.logo) {
            state.fileList = [
              {
                url: res.result.logo,
              },
            ];
          }
          if (res.result.associ_pois.length) {
            state.poiList = res.result.associ_pois;
            state.storeName = state.poiList.map((item) => item.id);
          }
        });
    };

    const sendModelRef = (state) => {
      for (let key in modelRef) {
        modelRef[key] = state[key];
      }
    };
    // 获取下拉列表
    const getSelectList = (val) => {
      state.fetching = true;
      let params = {};
      if (val) {
        params.keyword = val;
      } else {
        params.keyword = "";
      }
      request
        .get("/work_ai", "/user/shotstack/associ_poi/select/list", params)
        .then((res) => {
          state.selectList = res.result.map((item) => {
            return {
              label: item.store_name,
              value: item.id,
            };
          });
          state.selectData = res.result; //获取总数据
          state.fetching = false;
        })
        .catch(() => {
          state.fetching = false;
        })
        .finally(() => {
          state.fetching = false;
        });
    };
    // 下拉远程搜索
    const fetchUser = _.debounce((value) => {
      getSelectList(value);
    }, 300);
    // 下拉框change事件
    const selectChange = (value) => {
      const selectedItems = state.selectData.filter((item) =>
        state.storeName.includes(item.id)
      );

      const newData = selectedItems.filter((item) => {
        const existingItem = state.poiList.find((poi) => poi.id === item.id);
        return !existingItem;
      });
      const removedItems = state.poiList.filter(
        (poi) => !state.storeName.includes(poi.id)
      );
      const data = newData.map((item) => {
        return {
          id: item.id,
          poi_id: item.poi_id,
          poi_type: item.poi_type,
          store_address: item.store_address,
          store_name: item.store_name,
        };
      });
      state.poiList.push(...data); // 使用push方法将data追加到poiList数组中
      state.poiList = state.poiList.filter(
        (poi) => !removedItems.includes(poi)
      ); // 移除被取消勾选的项
    };
    return {
      ...toRefs(state),
      showModal,
      validateInfos,
      modelRef, imgUrl,
      dialog,
      cancelClick,
      submitClick,
      getFileList,
      handleUploadChange,
      handlePreview,
      addPOI,
      successPOI,
      editPOIClick,
      deletPOIClick,
      getSelectList,
      fetchUser,
      selectChange,
    };
  },
});
</script>

<style lang="less" scoped>
.poi-list {
  width: 100%;
  padding: 8px;
  border-radius: 6px;
  background: #efefef;
  margin-bottom: 10px;
}

.footer {
  width: 100%;
  text-align: center;
  margin-top: 20px;
}
</style>
